package com.fy.controller;


import com.alibaba.excel.EasyExcel;
import com.fy.aop.LogAnn;
import com.fy.entity.Channel;
import com.fy.entity.Result;
import com.fy.entity.User;
import com.fy.service.IChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 晓岩
 * @since 2022-06-14
 */
@RestController
@RequestMapping("/chan")
public class ChannelController {
    @Autowired
    IChannelService channelService;
    @LogAnn
    @RequestMapping("add")
    public Result add(@RequestBody Channel channel){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(!(principal instanceof User)) {
            return new Result(200, "", "匿名用户不能添加");
        }
        User loginUser = (User)principal;
        if(!"admin".equals(loginUser.getRole())){
            return new Result(201, "", "无权访问异常");
        }
        boolean b = channelService.save(channel);
        if(b){
            return new Result(200, "", "保存成功");
        }else{
            return new Result(202, "", "保存失败");
        }
    }
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        List<Channel> list = channelService.list();
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Channel.class).sheet("模板").doWrite(list);
    }
    @PostMapping("upload")
    @ResponseBody
    public String upload(MultipartFile[] file) throws IOException {
        for (MultipartFile multipartFile : file) {
            multipartFile.transferTo(new File("e:/test/"+multipartFile.getOriginalFilename()));
        }
        return "success";
    }
}
